package com.ljy.my_study.util;

/**
 * @author lijunying
 * @date 2021/11/18 11:10
 */
public class NodeUtil {

    public static NodeUtil.Node deserialize(String data) {
        if (data == null || data.isEmpty()) {
            return null;
        }
        String[] arrStr = data.split(",");
        NodeUtil.Node root = null;
        NodeUtil.Node[] NodeArr = new NodeUtil.Node[arrStr.length];
        for (int i = 0; i < arrStr.length; i++) {
            if (!arrStr[i].equals("#") && !arrStr[i].equals("null")) {
                Integer intVal = Integer.valueOf(arrStr[i]);
                NodeUtil.Node thisNode = new NodeUtil.Node(intVal);
                if (i == 0) {
                    root = thisNode;
                }
                NodeArr[i] = thisNode;
                if (i % 2 == 0) {
                    if (i / 2 - 1 >= 0) {
                        if (NodeArr[i / 2 - 1] != null) {
                            NodeArr[i / 2 - 1].right = thisNode;
                        }
                    }
                } else {
                    if ((i + 1) / 2 - 1 >= 0) {
                        if (NodeArr[(i + 1) / 2 - 1] != null) {
                            NodeArr[(i + 1) / 2 - 1].left = thisNode;
                        }
                    }
                }
            }
        }
        return root;
    }

    public static class Node {

        public int val;
        public Node left;
        public Node right;
        public Node next;

        public Node() {}

        public Node(int _val) {
            val = _val;
        }

        public Node(int _val, Node _left, Node _right, Node _next) {
            val = _val;
            left = _left;
            right = _right;
            next = _next;
        }
    }
}
